//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Spreadsheet.Expressions;
using OpenLS.Spreadsheet.Formats.Biff.Records;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    internal class StringConstantToken : FormulaToken
    {
        public StringConstantToken(string stringValue)
        {
            this._value = (ShortXLUnicodeString) stringValue;
           // _length = (ushort) ( stringValue.Length + 2); //\\unicode?
            _length = (ushort) _value.ByteLength;
        }

        private ushort _length;
        private ShortXLUnicodeString _value;

        public StringConstantToken()
        {
        }

        public override ushort GetLength(FormulaReadContextType formulaReadContextType)
        {

            return _length;
        }

        internal override void ReadContent(FormulaReadContext context)
        {
            _length = (ushort) context.BaseStream.Position;
            _value.Read(context.Reader);
            _length = (ushort) ((int) context.BaseStream.Position - _length);
        }
        public override void WriteContent(FormulaWriteContext context)
        {
           // Debug.WriteLine("_length == " + GetLength(context.Type));
#if DEBUG
            var position = context.Writer.BaseStream.Position;
#endif
            _value.Write(context.Writer);
#if DEBUG
            var position2 = context.Writer.BaseStream.Position;
            Contract.Assert(position2 - position == GetLength(context.Type));
#endif
        }

        public override FormulaTokenId TokenId
        {
            get { return FormulaTokenId.Str; }
        }

        internal override Expression GetExpression(FormulaEvaluationContext context)
        {
            return new StringConstantExpression((string) _value);
        }
    }
}